import 'package:file_selector/file_selector.dart';
import 'package:filelinker/file_model.dart';
import 'package:filelinker/mdsn.dart';
import 'package:filelinker/netsev.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:nsd/nsd.dart';

class FilesSendPage extends StatefulWidget {
  const FilesSendPage({super.key, required this.service, required this.files});

  final Service service;
  final List<XFile> files;

  @override
  State<FilesSendPage> createState() => _FilesSendPageState();
}

class _FilesSendPageState extends State<FilesSendPage> {
  final List<String> _uploadedNames = [];

  @override
  void initState() {
    super.initState();
    _uploadFiles();
  }

  @override
  void dispose() {
    EasyLoading.dismiss();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _wAppBar(),
      body: _wBodyView(),
    );
  }

  AppBar? _wAppBar() {
    bool isDesktop = MDNS.shared.isDesktop;
    TextStyle? ts = isDesktop ? Theme.of(context).textTheme.titleSmall : null;
    return AppBar(
      leading: isDesktop ? const CloseButton() : null,
      title: Text(widget.service.xname(), style: ts),
    );
  }

  Widget _wBodyView() {
    return ListView.separated(
      itemBuilder: (_, idx) {
        final name = widget.files[idx].name;
        return ListTile(
          leading: Icon(
            isImage(name) ? Icons.image : Icons.description,
          ),
          title: Text(
            name,
            overflow: TextOverflow.ellipsis,
            maxLines: 1,
          ),
          trailing: _wStatusView(name),
        );
      },
      itemCount: widget.files.length,
      separatorBuilder: (BuildContext context, int index) {
        return Divider(
          color: Theme.of(context).primaryColor.withAlpha((0.25 * 255).round()),
          height: 0.25,
        );
      },
    );
  }

  Widget _wStatusView(String name) {
    bool isDone = _uploadedNames.isNotEmpty && _uploadedNames.contains(name);
    return !isDone
        ? const CupertinoActivityIndicator()
        : Icon(
            Icons.done,
            color: Theme.of(context).primaryColor,
          );
  }

  Future<bool> _askFiles(String? address) async {
    if (address == null) return false;
    EasyLoading.show(status: "连接中...");
    debugPrint('address: $address');
    var state = await NetService.shared.askFiles(
      widget.files,
      address,
      widget.service.port,
      MDNS.shared.name,
    );
    EasyLoading.dismiss();
    return state == NetServiceState.accepted;
  }

  Future<String> _lookupAddress() async {
    String address = "";
    if (await _askFiles(widget.service.host)) {
      address = widget.service.host ?? "";
      return address;
    }
    if (widget.service.addresses != null) {
      for (var addr in widget.service.addresses!) {
        if (await _askFiles(addr.address)) {
          address = addr.address;
          break;
        }
      }
    }
    return address;
  }

  void _uploadFiles() async {
    String address = await _lookupAddress();

    if (address.isEmpty) {
      EasyLoading.showToast("连接失败，请重启app后重试", duration: const Duration(seconds: 120));
      return;
    }

    EasyLoading.showSuccess("连接成功，开始发送文件");

    for (var file in widget.files) {
      bool isDone = await NetService.shared.uploadFile(file, address, widget.service.port);
      if (isDone) {
        _uploadedNames.add(file.name);
        setState(() {});
      } else {
        EasyLoading.showError("${file.name} 发送失败");
      }
    }
  }
}
